//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package sw_dao

import (
	"context"

	"atomgit.com/openlinksaas-org/api-server/dao/db_ns"
	"atomgit.com/openlinksaas-org/proto-gen-go.git/sw_store_api"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type SoftWareCateInfoDbItem struct {
	CateId        string `bson:"_id" json:"_id"`
	CateName      string `bson:"cateName" json:"cateName"`
	Weight        uint32 `bson:"weight" json:"weight"`
	SoftWareCount uint32 `bson:"softWareCount" json:"softWareCount"`
	CreateTime    int64  `bson:"createTime" json:"createTime"`
	UpdateTime    int64  `bson:"updateTime" json:"updateTime"`
}

func (item *SoftWareCateInfoDbItem) ToSoftWareCateInfo() *sw_store_api.SoftWareCateInfo {
	return &sw_store_api.SoftWareCateInfo{
		CateId:        item.CateId,
		CateName:      item.CateName,
		Weight:        item.Weight,
		SoftWareCount: item.SoftWareCount,
		CreateTime:    item.CreateTime,
		UpdateTime:    item.UpdateTime,
	}
}

type _CateDao struct {
	mc *mongo.Collection
}

func newCateDao(db *mongo.Database) (*_CateDao, error) {
	mc := db.Collection(db_ns.DB_NS_SW_STORE + "cate")
	return &_CateDao{mc: mc}, nil
}

func (db *_CateDao) Insert(ctx context.Context, dbItem *SoftWareCateInfoDbItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_CateDao) Exist(ctx context.Context, cateId string) (bool, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"_id": cateId})
	return count > 0, err
}

func (db *_CateDao) Get(ctx context.Context, cateId string) (*SoftWareCateInfoDbItem, error) {
	retItem := &SoftWareCateInfoDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": cateId}).Decode(retItem)
	return retItem, err
}

func (db *_CateDao) Remove(ctx context.Context, cateId string) error {
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": cateId})
	return err
}

func (db *_CateDao) List(ctx context.Context) ([]*SoftWareCateInfoDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{}, options.Find().SetSort(bson.D{{"weight", -1}, {"updateTime", -1}}))
	if err != nil {
		return nil, err
	}
	retList := []*SoftWareCateInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_CateDao) Update(ctx context.Context, cateId, cateName string, weight uint32, updateTime int64) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": cateId},
		bson.M{"$set": bson.M{"cateName": cateName, "weight": weight, "updateTime": updateTime}})
	return err
}

func (db *_CateDao) UpdateSoftWareCount(ctx context.Context, cateId string, count uint32) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": cateId}, bson.M{"$set": bson.M{"softWareCount": count}})
	return err
}
